var $mainbody = $("#mainbody");
var $staffDialog = $('#staffDialog');
var $btnStaffConfirm = $('#btnStaffConfirm');
var $btnStaffReset = $('#btnStaffReset');

var $userStatus = $('#userStatus');//选择查看的当前用户的状态
var $userSearch = $('#userSearch');//输入进行模糊搜索的电话号码

//dialog elements
var $sCode = $('#sCode');
var $sName = $('#sName');
var $sPwd = $('#sPwd');
var $sPhone = $('#sPhone');
var OpType = {
	add: 0,
	update: 1
}

var menulist;//菜单列表
var setting = {
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};

var zNodes =[
// 			{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
];
/**
 * 添加管理员
 */
var addStaff = function(){
	var re = /^1\d{10}$/
	if (re.test($sPhone.val().trim())) {
	} else {
		alert("手机号格式错误");
		return;
	}

	var param = {
			staffCode: $sCode.val().trim(),
			name: $sName.val().trim(),
			phone: $sPhone.val().trim(),
			password: $sPwd.val().trim()
		}
	Ajax.ajax({
		url: '/staff/add',
		data: param,
		type: "POST",
		dataType: 'json',
		success:function(res){
			if (res.resultCode == 0) {
				alert('添加成功');
				$btnStaffReset.click();//重置按钮
				staffInfo.queryList();//刷新列表
				$staffDialog.hide();
			}else{
				alert('操作失败');
			}
		},
		error: function(){
			alert('操作失败');
		}
	});
}
/**
 * 修改管理员信息
 */
var updateStaff = function(){
	var param = {
		staffId: $sCode.attr('data-id'),
		name: $sName.val().trim(),
		phone: $sPhone.val().trim(),
		password: $sPwd.val().trim()
	}
	Ajax.ajax({
		url: '/staff/update',
		data: param,
		type: "post",
		dataType: 'json',
		success:function(res){
			 if (res.resultCode == 0) {
				alert('修改成功');
				$btnStaffReset.click();
				staffInfo.queryList();//刷新列表
				$staffDialog.hide();
			 }else{
			 	alert('操作失败');
			 }
		},
		error: function(){
			alert('操作失败');
		}
	});
}
/**
 * 打开添加\修改管理员对话框
 * @param opType 操作类型：添加 修改
 */
var editStaffInfo = function(opType){
	if(opType == OpType.add){
		$sCode.prop('disabled',false);
		$btnStaffConfirm.off('click');
		$btnStaffConfirm.on('click',addStaff);
	}else if(opType == OpType.update){
		$sCode.prop('disabled',true);
		$btnStaffConfirm.off('click');
		$btnStaffConfirm.on('click',updateStaff);
	}
	$staffDialog.show();//打开对话框
}

//分页信息
var staffInfo = {};
staffInfo.data = {
	pageSize:10,//每页记录数
	totalSize:0,//总记录数
	curPage:1,//当前页 1..n
	totalPage:0//总页数
};

//分页操作
staffInfo.page = {
	/**
	 * @description 转到第一页
	 * @author 
	 */
	turnFirst : function() {
		if(staffInfo.data.curPage == 1){
			promptMessge('已经是第一页',1000);
		}else{
			staffInfo.data.curPage = 1;
			//QueryResult();
		}
	},
	/**
	 * @description 转到尾页
	 * @author 
	 */
	turnEnd : function() {
		if(staffInfo.data.curPage == staffInfo.data.totalPage){
			promptMessge('已经是最后一页',1000);
		} else {
			staffInfo.data.curPage = staffInfo.data.totalPage;
			//QueryResult();
		}
	},
	/**
	 * @description 转到上页
	 * @author 
	 */
	turnPre : function() {
		if (staffInfo.data.curPage != 1) {
			staffInfo.data.curPage -= 1;
			//QueryResult();
		} else {
			promptMessge('已经是第一页',1000);
		}
	},
	/**
	 * @description 转到下页
	 * @author 
	 */
	turnNext : function() {
		if (staffInfo.data.curPage+1 <= staffInfo.data.totalPage) {
			staffInfo.data.curPage += 1;
			//QueryResult();
		} else {
			promptMessge('已经是最后一页',1000);
		}
	},
	//container 容器，count 总页数 pageindex 当前页数
	setPage : function (container, count, pageindex) {
		var container = container;
		var count = count;
		var pageindex = pageindex;
		var a = [];
		//总页数少于10 全部显示,大于10 显示前3 后3 中间3 其余....
		if (pageindex == 1) {
			a[a.length] = '<li class="disabled"><a>&lt;</a></li>';
		} else {
			a[a.length] = '<li><a>&lt;</a></li>';
		}
		function setPageList() {
			if (pageindex == i) {
				a[a.length] = '<li class="active"><a>' + i + '</a></li>';
			} else {
				a[a.length] = "<li><a>" + i + "</a></li>";
			}
		}

		//总页数小于10
		if (count <= 10) {
			for (var i = 1; i <= count; i++) {
				setPageList();
			}
		} else {
			//总页数大于10页
			if (pageindex <= 4) {
				for (var i = 1; i <= 5; i++) {
					setPageList();
				}
				a[a.length] = '<li class="disabled"><a>...</a></li><li><a>' + count + '</a></li>';
			} else if (pageindex >= count - 3) {
				a[a.length] = '<li><a>1</a></li><li class="disabled"><a>...</a></li>';
				for (var i = count - 4; i <= count; i++) {
					setPageList();
				}
			}
			else { //当前页在中间部分
				a[a.length] = '<li><a>1</a></li><li class="disabled"><a>...</a></li>';
				for (var i = pageindex - 2; i <= pageindex + 2; i++) {
					setPageList();
				}
				a[a.length] = '<li><a>...</a></li><li><a>' + count + '</a></li>';
			}
		}
		if (pageindex == count) {
			a[a.length] = '<li class="disabled"><a>&gt; </a></li>';
		} else {
			a[a.length] = "<li><a>&gt; </a></li>";
		}
		container.innerHTML = a.join("");

		//事件点击
		(function () {
			var oAlink = container.getElementsByTagName("a");
			var inx = pageindex; //初始的页码
			oAlink[0].onclick = function () { //点击上一页
				if (inx == 1) {
					return false;
				}
				inx--;
				staffInfo.page.setPage(container, count, inx);
				staffInfo.data.curPage = inx;
				//展示销售品列表
				staffInfo.queryList();
				return false;
			}
			for (var i = 1; i < oAlink.length - 1; i++) { //点击页码
				if(i === staffInfo.data.curPage){
					continue;
				}
				oAlink[i].onclick = function () {
					inx = parseInt(this.innerHTML);
					staffInfo.page.setPage(container, count, inx);
					staffInfo.data.curPage = inx;
					//展示销售品列表
//			    staffInfo.layOut.renderOfferList(staffInfo.data.categoryNodeId);
					staffInfo.queryList();
					return false;
				}
			}
			oAlink[oAlink.length - 1].onclick = function () { //点击下一页
				if (inx == count) {
					return false;
				}
				inx++;
				staffInfo.page.setPage(container, count, inx);
				staffInfo.data.curPage = inx;
				//展示销售品列表
//			  staffInfo.layOut.renderOfferList(staffInfo.data.categoryNodeId);
				staffInfo.queryList();
				return false;
			}
		})();
	}
};

/**
 * 设置页码
 */
staffInfo.renderPageInfo = function () {
	$(".pagination_c").empty();
	$(".pagination_c").append('<ul class="pagination"></ul>');
	staffInfo.page.setPage($(".pagination_c").find(".pagination")[0], staffInfo.data.totalPage, staffInfo.data.curPage);
};

/**
 * 获取用户数据
 */
staffInfo.queryList= function(){
	var param = {
		staff_code: $userSearch.val().trim(),
		status: $userStatus.val().trim(),
		cPage: staffInfo.data.curPage,
		pSize: staffInfo.data.pageSize
	};
	Ajax.ajax({
		url: "/staff/queryList",
		data: param,
		type: "post",
		dataType: 'json',
		success:function(res){
			if (res.resultCode == 0) {
				staffInfo.data.totalSize = res.data.totalRow;
				staffInfo.data.totalPage = res.data.totalPage;
				staffInfo.renderPageInfo();
				$(".page-pageno").html(staffInfo.data.curPage);
				$(".page-totalcount").html(staffInfo.data.totalSize);
				$(".page-pageno").html(staffInfo.data.curPage);
				$(".page-pagecount").html(staffInfo.data.totalPage);
				staffInfo.showTabel(res.data.list);
			}
		}

	});
}

/**
 * 展示用户数据
 * @param list
 */
staffInfo.showTabel= function(list){
	$mainbody.empty();

	$.each(list,function(n,v) {
		//开始组装
		var $tr = $("<tr>");
		var $checkbox = $('<td><input type="checkbox" data-id="' + v.staff_id + '"></td>');
		var $code = $('<td>' + v.staff_code + '</td>');
		var $name = $('<td>' + v.name + '</td>');
		var $phone = $("<td>" + v.phone + "</td>");

		var userStatus = parseInt(v.status) === 1 ? true : false;
		var $status = $("<td>" + (userStatus ? '正常' : '禁用') + "</td>");
		var $createDate = $("<td>" + v.create_date + "</td>");

		var $button1 = $('<button class="btn btn-primary btn-trans btn-xs btn-user-editor" data-id="' + v.staff_id +
			'" data-code="' + v.staff_code + '" data-name="'+ v.name +
			'" data-pwd="'+ v.password+ '" data-phone="'+ v.phone+ '">编辑</button>');
		var $button2 = $('<button class="btn btn-primary btn-trans btn-xs btn-user-del" data-id="' + v.staff_id + '">删除</button>');
		var $button3 = $('<button class="btn btn-primary btn-trans btn-xs btn-user-op" data-id="' + v.staff_id + '" data-status="' + v.status + '">' + (userStatus ? '禁用' : '启用') + '</button>');
        var $button4 = $('<button class="btn btn-primary btn-trans btn-xs btn-user-menu" data-id="' + v.staff_id + '">菜单配置</button>');
		var $btnTd;

		if(v.staff_id == "1"){
			$btnTd = $('<td>').append($button1,$button4);
		}else {
			$btnTd = $('<td>').append($button1,$button2,$button3,$button4);
		}
		$tr.append($checkbox, $code,$name, $phone, $createDate, $status,  $btnTd);
		$mainbody.append($tr);
	});

    //编辑
    $('button.btn-user-menu',$mainbody).on('click',function () {
        var $this = $(this);

        editMenuList($this.attr('data-id'));
    })

	//禁用\启用 按钮事件设置
	$('button.btn-user-op',$mainbody).on('click',function () {
		var userStatus = $(this).attr('data-status');
		var param = {
			staffId: $(this).attr('data-id'),
			u_status: userStatus == 0 ? 1 : 0
		}
		Ajax.ajax({
			url: "/staff/update",
			data: param,
			type: "POST",
			dataType: 'json',
			success: function (res) {
				if (res.resultCode == 0) {
					staffInfo.queryList();
				} else {
					alert("操作失败");
				}
			},
			error: function(){
				alert("操作失败");
			}
		});
	});
	//编辑
	$('button.btn-user-editor',$mainbody).on('click',function () {
		var $this = $(this);
		$sCode.attr('data-id',$this.attr('data-id'));
		$sCode.val($this.attr('data-code'));
		$sName.val($this.attr('data-name'));
		$sPwd.val($this.attr('data-pwd'));
		$sPhone.val($this.attr('data-phone'));
		editStaffInfo(OpType.update);
	})
	//删除
	$('button.btn-user-del',$mainbody).on('click',function () {
		if(confirm('确定删除该管理员？')){
			Ajax.ajax({
				url: "/staff/delete",
				data: {staffId: $(this).attr('data-id')},
				type: "POST",
				dataType: 'json',
				success:function(res){
					if (res.resultCode == 0) {
						staffInfo.queryList();
					}else{
						alert('操作失败');
					}
				},
				error: function(){
					alert('操作失败');
				}
			});
		}
		return false;
	})

	//选中当前行事件设置
	$('tr', $mainbody).on('click',function (e) {
		var $checkbox = $(this).find(':checkbox');
		if(e.target != $checkbox[0]){
			$checkbox.click();
		}
	});
}


var editMenuList= function(staffId){
    var param= {

        staffId:staffId
    };

    //初始化
    for(var i =0 ;i <zNodes.length; i++){

        zNodes[i].checked=false;

    }
    $.fn.zTree.init($("#treeDemo"), setting, zNodes);

    Ajax.ajax({
        url:"/staff/queryMenuByStaffId",
        data: param,
        type: "POST",
        dataType: 'json',
        async:false,
        success:function(res){
            debugger;

            if (res.resultCode == 0) {
                var mylist = res.data;
                debugger;
                for(var i =0 ;i <zNodes.length; i++){
                    for(var n = 0;n<mylist.length;n++){
                        if(mylist[n].menu_id==zNodes[i].id){
                            zNodes[i].checked=true;
                        }
                    }
                }
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);

				$("#menuList").attr("staffid",staffId).show();

            }else{
            }
        }

    });
}

$(function(){
	staffInfo.queryList();

	//选择查看的用户状态
	$userStatus.on('change',function(){
		staffInfo.queryList();
	});

	//查找按钮
	$('#userSearchBtn').on('click',function(){
		staffInfo.data.curPage = 1;
		staffInfo.queryList();
	});

	//每页显示的数据数切换
	$(".page-pagesize").change(function(){
		staffInfo.data.pageSize = $(this).val();
		staffInfo.data.curPage=1;
		staffInfo.queryList();
	});

	//表格头部选中全部
	$('#checkAll').on('click',function(){
		if(this.checked){
			//选中全部
			$mainbody.find(':checkbox').prop('checked', true);
		} else {
			$mainbody.find(':checkbox').prop('checked', false);
		}
	});

	//批量删除
	$('#btnDelAll').on('click',function(){
		var $userList = $mainbody.find(':checked');
		var l = $userList.length;
		if(l <= 0){
			alert('请先选择要删除的管理员');
		} else if(confirm('确认删除选中管理员？')) {
			var idList = Array.prototype.map.call($userList,function(obj){
				return obj.getAttribute('data-id');
			});
			var param = {
				staffIds: idList.join(',')
			}
			Ajax.ajax({
				url: "/staff/deleteBatch",
				data: param,
				type: "POST",
				dataType: 'json',
				success:function(res){
					if (res.resultCode == 0) {
						staffInfo.queryList();
					}else{
						alert('操作失败');
					}
				},
				error: function(){
					alert('操作失败');
				}
			});
		}
	});

	//添加管理员 打开添加窗口
	$('#btnAddManager').on('click',function(){
		editStaffInfo(OpType.add);
	});

	//关闭窗口
	$('#staffDialogClose').on('click',function(){
		$btnStaffReset.click();
		$staffDialog.hide();
	});

	$("#menuListClose").on('click',function(){

        $("#menuList").hide();
    });


    $("#btnMenuReset").on('click',function(){

        $("#menuList").hide();
    });

    $("#btnMenuConfirm").on('click',function(){

        var newList = "";


        var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
            nodes=treeObj.getCheckedNodes(true);
        for(var i=0;i<nodes.length;i++){
        	if(i==0){
                newList+=nodes[i].id;
			}else{
            	newList+=","+nodes[i].id;
            }
        }

        var param = {

            "menuList":newList,
			"staffId":$("#menuList").attr("staffid")
        };
        Ajax.ajax({
            url:"/staff/updateMenuById",
            data:param,
            dataType: 'json',
            type:"POST",
            success:function(res){
                debugger;

                if (res.resultCode == 0) {
                    alert("保存成功");
//  	   				ad.queryList();
                    $("#menuList").hide();
                }else{
                    alert("保存失败");
                }
            }

        });

    });



    Ajax.ajax({
        url:"/staff/queryMenuList",
        type:"POST",
        async:false,
        success:function(res){
            debugger;

            if (res.resultCode == 0) {
                 menuList = res.data;

                for( var x= 0;x<menuList.length;x++){
                    var node = { id:menuList[x].menu_id, pId:menuList[x].parent_menu_id, name:menuList[x].menu_name,  open:true};

                    zNodes.push(node);
                }

            }else{
            }
        }

    });


});